package com.junyuan.gsp.service;

import com.junyuan.gsp.bean.Menu;
import com.junyuan.gsp.bean.Result;
import com.junyuan.gsp.dao.MenuDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: maxwellens
 */
@Service
public class MenuService
{
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    public List<Menu> findRootMenus()
    {
        return menuDao.findRootMenus();
    }

    public List<Menu> findMenusByParentId(Integer id)
    {
        return menuDao.findMenusByParentId(id);
    }

    public List<Menu> findOwnedTreeMenus(Integer userId)
    {
        List<Integer> menus = userService.findOwnedMenus(userId);
        List<Menu> rootMenus = filterMenus(findRootMenus(), menus);
        for (Menu menu : rootMenus)
        {
            List<Menu> children = findMenusByParentId(menu.getId());
            menu.setChildren(filterMenus(children, menus));
        }
        return rootMenus;
    }

    public List<Menu> findMenus()
    {
        return menuDao.findMenus();
    }

    public Integer findMenusCount()
    {
        return menuDao.findMenusCount();
    }

    public Result findMenusResult()
    {
        int count = menuDao.findMenusCount();
        List<Menu> data = menuDao.findMenus();
        return new Result(data, count);
    }

    public Menu findMenuById(Integer id)
    {
        return menuDao.findMenuById(id);
    }

    public void saveMenu(Menu menu)
    {
        if (menu.getId() != null && menu.getId() != 0)
        {
            menuDao.updateMenu(menu);
        } else
        {
            menuDao.insertMenu(menu);
        }
    }

    public void deleteMenuById(Integer id)
    {
        menuDao.deleteMenuById(id);
    }

    public void deleteMenuByIdCascade(Integer id)
    {
        menuDao.deleteMenuById(id);
        List<Menu> childMenus = menuDao.findMenusByParentId(id);
        for (Menu menu : childMenus)
        {
            deleteMenuByIdCascade(menu.getId());
        }
    }

    /**
     * @param menus     待过滤的菜单项列表
     * @param filterIds 需要保留的MenuIds
     * @return 已过滤的菜单项列表
     */
    private List<Menu> filterMenus(List<Menu> menus, List<Integer> filterIds)
    {
        List<Menu> result = new ArrayList<>();
        for (Menu menu : menus)
        {
            if (filterIds.contains(menu.getId()))
            {
                result.add(menu);
            }
        }
        return result;
    }

}
